import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";

import {getPermissionListType} from "@/network/permission";
import {getUserInfoByMySelf} from "@/network/adminUser";
import {SET_LOGIN_STATUE, SET_USERINFO} from "@/store/mutations-type";


const Index = () => import('@/views/Index')
const Register =() => import('@/components/conment/register/Register')
const OrderRoom =() => import('@/views/order/Order')

const Admin = () => import('@/views/admin/Admin')
const DashBoard = () => import('@/views/admin/childComps/dashboard/DashBoard')
const UserInfo =() => import('@/views/admin/childComps/UserInfo')
const User = () => import('@/views/user/User')
const UserCenter =() =>import('@/views/user/childComps/UserCenter')
const UserOrder =() =>import('@/views/user/childComps/UserOrder')
const UserProfile =() =>import('@/views/user/childComps/UserProfile')

Vue.use(VueRouter)

//解决报错Redirected when going from "/xxx" to "/yyy" via a navigation guard.
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Index',
    component:Index,
  },
  {
    path: '/order',
    name: 'OrderRoom',
    component:OrderRoom,
  },
  {
    path: '/register',
    name: 'Register',
    component:Register,
  },
  {
    path: '/user/',
    name: 'User',
    component:User,
    children: [
      {
        path: 'center',
        name: 'UserCenter',
        component: UserCenter,
      },
      {
        path: 'order',
        name: 'UserOrder',
        component: UserOrder,
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: UserProfile,
      },
    ]
  },
  {
    path: '/admin/',
    name: 'Admin',
    component:Admin,
    children: [
      {
        path: 'dashboard',
        name: 'DashBoard',
        component:DashBoard,
      },
      {
        path: 'userinfo',
        name: 'UserInfo',
        component:UserInfo,
      }
    ],
  }
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//路由前置拦截
router.beforeEach((to,from,next)=>{
  let hasRoute = store.getters.getHasRoutes
  let token = localStorage.getItem("token")
  if (to.path === '/' || to.path === '/index' || to.path === '/register'){//放行
    // next()
  } else if(!token){//没有token 就跳转到主页
    next({path: '/'})
  }else if (token && to.path.startsWith('/user/')){//普通用户

  }else if(token && !hasRoute){//token存在 无路由标志
    //获取当前用户角色下的所有权限菜单数据
    getPermission()
  }else {
    // next()
  }
  getUserInfo().then(r => {next()})
})
//生成路由
const toRoute = (menu) => {
  if (!menu.component) {
    return null
  }
  let route = {
    name: menu.resourceName,
    path: menu.resourceUrl,
  }
  route.component = () => import('@/views/admin/childComps/' + menu.component +'.vue')
  return route
}
const getUserInfo = async function (){
  if(localStorage.getItem("token") && !Object.keys(store.getters.getUserInfo).length){//token存在 无用户信息
    //如果登录了 用户刷新后 丢失userInfo
    await getUserInfoByMySelf().then(async res=>{
      await store.commit(SET_USERINFO,res.data.data)//存储用户信息
      await store.commit(SET_LOGIN_STATUE,true)//设置登录状态
    })
  }
}
const getPermission = function(){
  getPermissionListType().then( res=>{
    store.dispatch("initRouteAndPermission", {
      'menuList': res.data.data.menuList,
      'permissionList': res.data.data.permissionList
    }).then(() =>{})
    res.data.data.menuList.forEach(menu => {
      if (menu.childList) {
        menu.childList.forEach(e => {
          router.addRoute('Admin',toRoute(e))
        })
      }
    })
    store.commit('changeRouteStatue',true)
  })
}

export default router
